import React, { Component } from 'react';
import {Image, StyleSheet, Text, View, TextInput, ScrollView, TouchableOpacity, DeviceEventEmitter, Platform} from 'react-native';
import Confirm from '../../../components/confirm/Confirm'
import ReactNativePickerSelect from 'react-native-picker-select'
import Toast from 'react-native-easy-toast'
import Loading from '../../../components/loading/index'
import { API } from "../../../api";
import {i18n} from "../../../utils/locales/i18n";

type Props = {};
export default class AdvertisePublish extends Component<Props> {
    static navigationOptions = ({ navigation }) => {
        return {
            title: i18n.t('i184'),
            headerTintColor: '#0f0f0f',
            headerBackTitle: null
        }
    }
    constructor() {
        super()
        this.state = {
            ad_price: '',
            modalVisible: false,
            defeatModalVisible: false,
            loading: false,
            currentToastInfo: '',
            // 广告类型
            adType: '0',
            // 交易银行卡号
            txBankNum: '',

            min: '',
            max: '',
            unit: '',

            // 初始化数据
            // 手续费
            fee: '',
            // 限额
            adLimit: '',
            // 银行卡列表
            bankList: '',
            // 市场极限价
            marketPrice: '',
            marketPrice2: ''
        }
    }
    componentDidMount(): void {
        this._initData()
    }

    _initData = async () => {
        this.setState({
            loading: true
        })
        const [adFeeRes, adLimitRes, bankListRes, marketPriceRes, marketPriceRes2] = await Promise.all([
            API._fetch('getAdFee', {}, 'GET'),
            API._fetch('getAdLimit', { token: this.state.adType === '0' ? "fcc" : 'hkd' }),
            API._fetch('getBank', {}, 'GET'),
            API._fetch('getMarketPrice', {
                "type": 2,
                "sellToken": 'fcc',
                "buyToken": 'hkd'
            }),
            API._fetch('getMarketPrice', {
                "type": 1,
                "sellToken": "hkd",
                "buyToken": "fcc"
            })
        ])
        // console.log(adFeeRes, adLimitRes, bankListRes, marketPriceRes, marketPriceRes2)
	    this.setState({
		    loading: false
	    })
        if (bankListRes.data.length > 0) {
            bankListRes.data.forEach(item => {
                item.label = item.Number
                item.value = item.Id
            })
        } else {
            this.setState({
                modalVisible: false
            })
        }
        this.setState({
            fee: Number(adFeeRes.data) * 100,
            adLimit: adLimitRes.data,
            bankList: bankListRes.data,
            marketPrice: marketPriceRes.data ? marketPriceRes.data.Price : '----',
            marketPrice2: marketPriceRes2.data ? marketPriceRes2.data.Price : '----'
        })
        this.setState({
            loading: false
        })
        // 0:
        // code: 10000
        // data: 0.005
        // msg: "获取信息成功"
        // status: 200
        // __proto__: Object
        // 1:
        // code: 10000
        // data:
        //     Max: 10000
        // Min: 10
        // __proto__: Object
        // msg: "获取信息成功"
        // status: 200
        // __proto__: Object
        // 2:
        // code: 10000
        // data: [
            // 0:
            // Id: 34
            // Name: "Niudiedie"
            // Number: "6221888200604489572"
            // Uid: 0
        // ]
        // msg: "获取信息成功"
        // status: 200
        // __proto__: Object
        // 3:
        // code: 10000
        // data:
        //     Price: 2
        // __proto__: Object
        // msg: "获取信息成功"
        // status: 200

    }
    // 执行发布广告
    publishAd = async () => {
        // 购买参数
            // bankId: 34
            // buyToken: "fcc"
            // max: "344"
            // min: "32"
            // sellToken: "hkd"
            // type: 1
            // unit: "21"
        // 出售参数
            // bankId: 34
            // buyToken: "hkd"
            // max: "234"
            // min: "43"
            // sellToken: "fcc"
            // type: 2
            // unit: "43"
        if (!this.state.txBankNum) {
            this.refs.toast.show(i18n.t('i83'))
            return
        }
        if (!this.state.max || !this.state.min || !this.state.unit) {
            this.refs.toast.show(i18n.t('plz_cpl'))
            return
        }
        if (Number(this.state.min) > Number(this.state.max)) {
            this.refs.toast.show(i18n.t('i160'))
            return
        }
        if (Number(this.state.min) < Number(this.state.adLimit.Min) || Number(this.state.max) > Number(this.state.adLimit.Max)) {
            this.refs.toast.show(i18n.t('overflow'))
            return
        }
        const reqData = {
            bankId: this.state.txBankNum,
            buyToken: this.state.adType === '0' ? "fcc" : 'hkd',
            max: this.state.max,
            min: this.state.min,
            sellToken: this.state.adType === '0' ? "hkd" : 'fcc',
            type:  this.state.adType === '0' ? 1 : 2,
            unit: this.state.unit
        }
        // console.log('resData', resData);
        if (!this.state.bankList) {
            this.setState({
                modalVisible: true
            })
        }
        this.setState({
            loading: true
        })
        const res = await API._fetch('publishAd', reqData)
        this.setState({
            loading: false
        })
        // console.log('rs321321', res);
        if (res.code === 10000) {
            this.refs.toast.show(res.msg || i18n.t('o_success'))
            DeviceEventEmitter.emit('refresh_ad');
            setTimeout(() => {
                this.props.navigation.goBack()
            }, 1000)
        } else {
            this.refs.toast.show(res.msg || i18n.t('o_defeat'))
        }
    }

    // 确认发布广告
    handleCancel = () => {
        this.setState({
            modalVisible: false
        })
    }
    handleConfirm = () => {
        this.setState({
            modalVisible: false,
            // defeatModalVisible: true
        })
        this.publishAd()
    }
    // 发布广告失败处理
    handleIKnow = () => {
        this.setState({
            defeatModalVisible: false
        })
    }
    // 切换广告类型
    changeAdType = async (type) => {
        this.setState({
            adType: type,
            loading: true
        })
        // 重新获取
        setTimeout(async () => {
            const [ adLimitRes, marketPriceRes ] = await Promise.all([
                API._fetch('getAdLimit', { token: this.state.adType === '0' ? "fcc" : 'hkd' }),
                API._fetch('getMarketPrice', {
                    "type": this.state.adType === '0' ? 1 : 2,
                    "sellToken": this.state.adType === '0' ? "hkd" : 'fcc',
                    "buyToken": this.state.adType === '0' ? "fcc" : 'hkd'
                })
            ])
            this.setState({
                adLimit: adLimitRes.data,
                marketPrice: marketPriceRes.data ? marketPriceRes.data.Price : marketPriceRes.msg
            })
            this.setState({
                loading: false
            })
        }, 0)
    }
    render() {
        return (
            <View style={{ flex: 1 }}>
                {/*toast*/}
                <Toast ref="toast" position='bottom' positionValue={200}/>
                { this.state.loading ? (
                    <Loading
                        info={this.state.currentToastInfo}
                    />) : null }
                <View style={[styles.container, { borderBottomWidth: 10, borderBottomColor: '#f2f2f2' }]}>
                    <View style={{ paddingVertical: 15 }}>
                        <View>
                            <Text style={{ fontSize: 13, lineHeight: 22, color: '#808080' }}>{i18n.t('i185')}
                                <Text style={{ color: '#2c61f8' }} onPress={() => this.props.navigation.navigate('Advertisement')}>{i18n.t('i162')}</Text>
                                {i18n.t('i237')}</Text>
                        </View>
                        <View>
                            <Text style={{ fontSize: 13, lineHeight: 22, color: '#808080' }}>{i18n.t('i164')}{ this.state.fee }%。 </Text>
                        </View>
                        <View>
                            <Text style={{ fontSize: 13, lineHeight: 22, color: '#808080' }}>{i18n.t('i165')}</Text>
                        </View>
                    </View>
                    {/*select item wrapper*/}
                    <View>
                        {/*select item*/}
                        <View style={{ height: 50, width: '100%', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', borderTopColor: '#eee', borderTopWidth: 0.5 }}>
                            <View style={{ justifyContent: 'center', alignItems: 'center' }}>
                                <Text style={{ color: '#0f0f0f', fontSize: 16 }}>{i18n.t('i166')}</Text>
                            </View>
                            <TouchableOpacity style={{ flex: 1, height: '100%', justifyContent: 'center' }}>
                                <View style={{ width: '100%', flexDirection: 'row', justifyContent: 'flex-end' }}>
                                    <View style={{ flexDirection: 'row', alignItems: 'center', position: 'relative', borderWidth: 0 }}>
                                        <ReactNativePickerSelect
                                            style={{...pickerSelectStyles}}
                                            underlineColorAndroid="transparent"
                                            items={[
                                                { label: i18n.t('i167'), value: '0' },
                                                { label: i18n.t('i168'), value: '1' }
                                            ]}
                                            value={this.state.adType}
                                            hideIcon={true}
                                            // onValueChange={(adType) => {this.setState({adType})}}
                                            onValueChange={(adType) => this.changeAdType(adType)}
                                        />
                                        <Image resizeMode={'contain'} style={{width: 10, height: 10, position: 'absolute', top: '40%', right: 5}} source={require('@images/mine/icon_triangle.png')}/>
                                        {/*<Image style={{width: 10, height: 10}} source={require('../../../images/adver/arrow.png')}/>*/}
                                    </View>
                                </View>
                            </TouchableOpacity>
                        </View>
                        <View style={{ height: 60, width: '100%', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', borderTopColor: '#eee', borderTopWidth: 0.5 }}>
                            <View style={{ justifyContent: 'center', alignItems: 'center' }}>
                                { this.state.adType === '0' ? (
                                    <Text style={{ color: '#0f0f0f', fontSize: 16 }}>{i18n.t('i169')}</Text>
                                ) : (
                                    <Text style={{ color: '#0f0f0f', fontSize: 16 }}>{i18n.t('i170')}</Text>
                                ) }
                            </View>
                            <TouchableOpacity style={{ flex: 1, height: '100%', justifyContent: 'center' }}>
                                <View style={{ width: '100%', flexDirection: 'row', justifyContent: 'flex-end', paddingRight: 10 }}>
                                    <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                                        <Text style={{ color: '#808080' }}>FCC</Text>
                                        {/*<Image style={{width: 10, height: 10}} source={require('../../../images/adver/arrow.png')}/>*/}
                                    </View>
                                </View>
                            </TouchableOpacity>
                        </View>
                        <View style={{ height: 60, width: '100%', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', borderTopColor: '#eee', borderTopWidth: 0.5 }}>
                            <View style={{ justifyContent: 'center', alignItems: 'center' }}>
                                <Text style={{ color: '#0f0f0f', fontSize: 16 }}>{i18n.t('i171')}</Text>
                            </View>
                            <TouchableOpacity style={{ flex: 1, height: '100%', justifyContent: 'center' }}>
                                <View style={{ width: '100%', flexDirection: 'row', justifyContent: 'flex-end', paddingRight: 10 }}>
                                    <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                                        <Text style={{ color: '#808080' }}>HKD</Text>
                                        {/*<Image style={{width: 10, height: 10}} source={require('../../../images/adver/arrow.png')}/>*/}
                                    </View>

                                </View>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
                <ScrollView style={[styles.container, { flex: 1}]}>
                    <View style={{ width: '100%' }}>
                        {/*list item*/}
                        <View style={[styles.container, { borderBottomWidth: 0.5, borderBottomColor: '#eee', flexDirection: 'row', alignItems: 'center', height: 50 }]}>
                            <View style={{ width: '30%' }}><Text>{i18n.t('i172')}</Text></View>
                            <View style={{ flex: 1 }}>
                                <TextInput
                                    style={{height: '100%', width: '100%', borderLeftWidth: 0.5, borderLeftColor: '#eee', paddingLeft: 20}}
                                    onChangeText={(unit) => this.setState({unit})}
                                    placeholder={i18n.t('i236')}
                                    keyboardType={'numeric'}
                                    value={this.state.unit}
                                />
                            </View>
                            <View>
                                <Text style={{color: '#808080'}}>HKD</Text>
                            </View>
                        </View>
                        {/*售价提示*/}
                        { this.state.adType == '0' ? (
                            <View style={[styles.container, { height: 40, justifyContent: 'center', borderBottomColor: '#eee', borderBottomWidth: 0.5 }]}>
                                <Text style={{ color: '#ff7606' }}>{i18n.t('i174')}：<Text>{ this.state.marketPrice2 }</Text></Text>
                            </View>
                        ) : (
                            <View style={[styles.container, { height: 40, justifyContent: 'center', borderBottomColor: '#eee', borderBottomWidth: 0.5 }]}>
                                <Text style={{ color: '#ff7606' }}>{i18n.t('i173')}：<Text>{ this.state.marketPrice || 2 }</Text></Text>
                            </View>
                        ) }
                        {/*交易限制设置*/}
                        <View style={[styles.container, { width: '100%', height: 60, flexDirection: 'row', alignItems: 'center' }]}>
                            <Image source={require('../../../images/adver/icon-setting.png')} style={{ width: 20, height: 20, marginRight: 10 }}/>
                            <Text style={{ fontSize: 16 }}>{i18n.t('i175')}</Text>
                        </View>
                        <View style={{ height: 60, width: '100%', flexDirection: 'row', borderBottomWidth: 0.5, borderBottomColor: '#eee', justifyContent: 'space-between', alignItems: 'center', borderTopColor: '#eee', borderTopWidth: 1 }}>
                            <View style={{ justifyContent: 'center', alignItems: 'center' }}>
                                <Text style={{ color: '#0f0f0f', fontSize: 16 }}>{i18n.t('i176')}</Text>
                            </View>
                            <TouchableOpacity style={{ flex: 1, height: '100%', justifyContent: 'center' }}>
                                <View style={{ width: '100%', flexDirection: 'row', justifyContent: 'flex-end' }}>
	                                <View style={{position: 'relative', width: '100%', borderWidth: Platform.OS === 'ios' ? 0 : 0.5, borderColor: '#d2d2d2', borderRadius: 5, borderBottomLeftRadius: 0, borderTopLeftRadius: 0, height: 40 }}>
                                        {this.state.bankList ? (
                                            <ReactNativePickerSelect
                                                style={{...pickerSelectStyles}}
                                                items={this.state.bankList}
                                                value={this.state.txBankNum}
                                                hideIcon={true}
                                                placeholder={{
                                                    label: i18n.t('i134'),
                                                    value: null,
                                                    color: '#9EA0A4',
                                                }}
                                                onValueChange={(txBankNum) => {this.setState({txBankNum})}}
                                            />
                                        ) : null}
                                        <Image resizeMode={'contain'} style={{width: 10, height: 10, position: 'absolute', top: '40%', right: 5}} source={require('@images/mine/icon_triangle.png')}/>
                                        {/*<Image style={{width: 10, height: 10}} source={require('../../../images/adver/arrow.png')}/>*/}
                                    </View>
                                </View>
                            </TouchableOpacity>
                        </View>
                        {/*最小限额*/}
                        <View style={[styles.container, { borderBottomWidth: 0.5, borderBottomColor: '#eee', flexDirection: 'row', alignItems: 'center', height: 50 }]}>
                            <View style={{ width: '30%' }}><Text>{i18n.t('i177')}</Text></View>
                            <View style={{ flex: 1 }}>
                                <TextInput
                                    style={{height: '100%', width: '100%', borderLeftWidth: 0.5, borderLeftColor: '#eee', paddingLeft: 20}}
                                    onChangeText={(min) => this.setState({min})}
                                    // placeholder={'输入最小限额'}
                                    keyboardType={'numeric'}
                                    value={this.state.min}
                                />
                            </View>
                            { this.state.adType === '0' ? (
                                <View>
                                    <Text style={{color: '#808080'}}>FCC</Text>
                                </View>
                            ) : (
                                <View>
                                    <Text style={{color: '#808080'}}>HKD</Text>
                                </View>
                            ) }
                        </View>
                        <View style={[styles.container, { height: 40, justifyContent: 'center', borderBottomColor: '#eee', borderBottomWidth: 0.5 }]}>
                            <Text style={{ color: '#ff7606' }}>{i18n.t('i178')}:
                                <Text>{ this.state.adLimit ? this.state.adLimit.Min : '---' }</Text>
                            </Text>
                        </View>
                        {/*最大限额*/}
                        <View style={[styles.container, { borderBottomWidth: 0.5, borderBottomColor: '#eee', flexDirection: 'row', alignItems: 'center', height: 50 }]}>
                            <View style={{ width: '30%' }}><Text>{i18n.t('i179')}</Text></View>
                            <View style={{ flex: 1 }}>
                                <TextInput
                                    style={{height: '100%', width: '100%', borderLeftWidth: 0.5, borderLeftColor: '#eee', paddingLeft: 20}}
                                    onChangeText={(max) => this.setState({max})}
                                    // placeholder={'输入最大限额'}
                                    keyboardType={'numeric'}
                                    value={this.state.max}
                                />
                            </View>
                            { this.state.adType === '0' ? (
                                <View>
                                    <Text style={{color: '#808080'}}>FCC</Text>
                                </View>
                            ) : (
                                <View>
                                    <Text style={{color: '#808080'}}>HKD</Text>
                                </View>
                            ) }
                        </View>
                        <View style={[styles.container, { height: 40, justifyContent: 'center', borderBottomColor: '#eee', borderBottomWidth: 0.5 }]}>
                            <Text style={{ color: '#ff7606' }}>{i18n.t('i180')}:
                                <Text>{ this.state.adLimit ? this.state.adLimit.Max : '---' }</Text>
                            </Text>
                        </View>
                    </View>
                </ScrollView>
                {/*发布广告按钮*/}
                <TouchableOpacity onPress={ () => this.publishAd() } style={{ height: 50 }}>
                    <View style={{ flex: 1, backgroundColor: '#ff7606', justifyContent: 'center', alignItems: 'center' }}>
                        <Text style={{ color: '#fff', fontSize: 16 }}>{i18n.t('i184')}</Text>
                    </View>
                </TouchableOpacity>
                {/*发布广告弹框确认*/}
                <Confirm
                    title={i18n.t('info')}
                    negative={i18n.t('cancel')}
                    positive={i18n.t('confirm')}
                    modalVisible={this.state.modalVisible}
                    handleCancelOrder={this.handleIKnow}
                    handleConfirmOrder={this.handleConfirm}
                >
                    <View style={{flex: 1, paddingVertical: 10}}>

                        <View style={{flex: 1, paddingVertical: 10, justifyContent: 'center', alignItems: 'center'}}>
                            <Text style={{ fontSize: 16, color: '#808080' }}>{i18n.t('i182')}</Text>
                            <Text style={{ fontSize: 16, color: '#808080' }}>{i18n.t('i183')}</Text>
                        </View>
                    </View>
                </Confirm>
                {/*发布广告失败*/}
                {/*<Confirm*/}
                    {/*title={'提示'}*/}
                    {/*negative={'我知道了'}*/}
                    {/*isSingleButton={true}*/}
                    {/*modalVisible={true}*/}
                    {/*handleCancelOrder={this.handleIKnow}*/}
                {/*>*/}
                    {/*<View style={{flex: 1, paddingVertical: 10, justifyContent: 'center', alignItems: 'center'}}>*/}
                        {/*<Text style={{ fontSize: 16, color: '#808080' }}>未进行实名认证/未绑定银行卡</Text>*/}
                        {/*<Text style={{ fontSize: 16, color: '#808080' }}>请前往【我的】页面进行认证</Text>*/}
                    {/*</View>*/}
                {/*</Confirm>*/}
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        paddingHorizontal: 10
    }
});

const pickerSelectStyles = StyleSheet.create({
    inputIOS: {
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: 40,
        paddingHorizontal: 10,
        borderWidth: 0,
        borderColor: '#d2d2d2',
        borderRadius: 5,
        borderBottomLeftRadius: 0,
        borderTopLeftRadius: 0,
        backgroundColor: 'white',
        color: '#808080',
        marginVertical: 5,
        paddingRight: 25
    },
    inputAndroid: {
	    display: 'flex',
	    flexDirection: 'row',
	    justifyContent: 'space-between',
	    alignItems: 'center',
	    height: 30,
	    width: 200,
	    padding: 0,
	    margin: 0,
	    borderWidth: 0.5,
	    borderColor: '#d2d2d2',
	    borderRadius: 5,
	    borderBottomLeftRadius: 0,
	    borderTopLeftRadius: 0,
	    backgroundColor: 'white',
	    color: '#808080',
	    marginVertical: 5
    }
});
